package ge;

import java.lang.reflect.InvocationTargetException;

import org.codehaus.janino.CompileException;
import org.codehaus.janino.ExpressionEvaluator;
import org.codehaus.janino.Parser.ParseException;
import org.codehaus.janino.Scanner.ScanException;

public abstract class CodeEvaluator<T> {
	private ExpressionEvaluator _evalutator;

	public CodeEvaluator(String code, Class<T> return_type,
			String[] parameter_names, Class<?>[] parameter_types) {
		code = getStartCode() + code + getEndCode();

		try {
			_evalutator = new ExpressionEvaluator(code, return_type,
					parameter_names, parameter_types);
		} catch (CompileException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ScanException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public T execute(Object[] parameters) {
		Object ret = null;

		try {
			ret = _evalutator.evaluate(parameters);
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return (T) ret;
	}

	public abstract String getStartCode();

	public abstract String getEndCode();
}
